package org.springblade.modules.admin.utils;

import cn.hutool.core.io.IORuntimeException;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import org.springblade.core.log.exception.ServiceException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 专门处理腾讯云的数据
 *
 * @author zcc
 * @version 1.0
 * @date 2022/6/20 9:55
 */
@Component
public class TlwEmsUtil {

	@Value("${ems.url}")
	private String tlwUrl;

	@Value("${ems.timeout}")
	private Integer timeout;

	/**
	 * get请求
	 * @param url
	 * @param param
	 * @return
	 */
	public String get(String url, Map<String, Object> param) {
		HttpResponse res = null;
		if (param == null) {
			res = HttpRequest.get(tlwUrl + url).timeout(timeout).execute();
		} else {
			res = HttpRequest.get(tlwUrl + url).form(param).timeout(timeout).execute();
		}

		try {
			if (res.getStatus() == 404) {
				return null;
			}
			return res.body();
		}catch (IORuntimeException e) {
			throw new ServiceException("梯联网数据返回异常!");
		}
	}

	/**
	 * post请求
	 * @param url
	 * @param params
	 * @return
	 */
	public String post(String url, String params) {
		HttpResponse res = HttpRequest.post(tlwUrl + url).body(params).timeout(timeout).execute();
		try {
			if (res.getStatus() == 404) {
				return null;
			}
			return res.body();
		}catch (IORuntimeException e) {
			throw new ServiceException("梯联网数据返回异常!");
		}
	}
}
